package com.errol.generic.sms.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.renjia.pojo.MyMobileValidator;
import com.renjia.service.generic.ali.sms.model.AliSmsRequest;
import com.renjia.service.generic.ali.sms.model.AliSmsResult;
import com.renjia.service.generic.log.LogService;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by Errol on 19/08/26.
 */
@Service
public class AliSmsServiceImpl implements AliSmsService {

    private final String accessKeyId = "LTAIj0NZIjPfkjU4";
    private final String accessKeySecret = "yh8M5HtZMRnQz5Llp0HtzZDDyluXNc";
    private final LogService logService;

    public AliSmsServiceImpl(LogService logService) {
        this.logService = logService;
    }

    @Override
    public AliSmsResult send(@NonNull String signName, @NonNull String mobile, @NonNull String templateCode, @Nullable Map<String, String> templateParams) {
        try {
            String templateParamsStr = templateParams == null ? "" : new ObjectMapper().writeValueAsString(templateParams);
            if (!new MyMobileValidator().isValid(mobile, null)) {
                return new AliSmsResult(-1, "手机号错误");
            }
            SendSmsResponse response = send(new AliSmsRequest(signName, mobile, templateCode, templateParamsStr));
            if (!response.getCode().equals("OK")) {
                logService.warn("发送短信失败，手机号：" + mobile + "，模板code：" + templateCode
                        + "，返回code=" + response.getCode() + "，msg=" + response.getMessage() + "，回执id=" + response.getBizId());
            }
            return new AliSmsResult(response.getCode().equals("OK"));
        } catch (Exception e) {
            logService.warn("发送短信异常！");
            logService.warn(e);
            return new AliSmsResult(true);
        }
    }

    private SendSmsResponse send(AliSmsRequest aliSmsRequest) throws ClientException {
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
        IAcsClient acsClient = new DefaultAcsClient(profile);

        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(aliSmsRequest.getPhoneNumbers());
        smsRequest.setSignName(aliSmsRequest.getSignName());
        smsRequest.setTemplateCode(aliSmsRequest.getTemplateCode());
        smsRequest.setTemplateParam(aliSmsRequest.getTemplateParams());

        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
//        smsRequest.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
//        smsRequest.setOutId("yourOutId");

        return acsClient.getAcsResponse(smsRequest);
    }

}
